package com.lxy.aimin.ds.translate;

import com.lxy.aimin.ds.annotation.DictTranslate;
import com.lxy.aimin.ds.entity.Dict;
import com.lxy.aimin.ds.service.DictService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.context.annotation.Lazy;

import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.List;

/*
 *
 * @author 渣哥
 */
@Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
@RequiredArgsConstructor(onConstructor = @__(@Lazy))
public class DictTranslateInterceptor implements Interceptor {


    private final DictService dictService;


    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        //1. 查询出数据来
        //2. 遍历字段，是否有@DictTranslate注解
        //3. 如果有，获取注解的valueTo Key
        //4. dict表中查询出valueTo的值
//        System.out.println("拦截器执行了");
        // 查询出来的数据
        Object result = invocation.proceed();  //动态代理

        if(result instanceof List){
            for(Object object : (List<?>)result) {
                Class<?> clazz = object.getClass();
                Field[] declaredFields = clazz.getDeclaredFields();
                for(Field field : declaredFields){
                    if(field.isAnnotationPresent(DictTranslate.class)){
                        DictTranslate annotation = field.getAnnotation(DictTranslate.class);
                        String targetField = annotation.valueTo();
                        field.setAccessible(true);
                        Object value = field.get(object);
                        Field declaredField = clazz.getDeclaredField(targetField);
                        Dict byId = dictService.getById((int) value);
                        if(null != byId){
                            String dictName = byId.getDictName();
                            declaredField.setAccessible(true);
                            declaredField.set(object, dictName);
                        }
                    }
                }
            }
        }
        // 查询前 修改sql ,添加分页语句
        return result;
    }

}
